package carmesi.wizards;

import java.awt.Component;
import java.util.Iterator;
import java.util.Set;
import java.util.concurrent.CopyOnWriteArraySet;
import javax.swing.event.ChangeEvent;
import javax.swing.event.ChangeListener;
import org.openide.WizardDescriptor;
import org.openide.util.HelpCtx;

/**
 *
 * @author Victor
 */
public class CarmesiPanel implements WizardDescriptor.Panel<WizardDescriptor> {

    private Component component;
    private ComponentValidator validator;
    private Set<ChangeListener> listeners = new CopyOnWriteArraySet<ChangeListener>();
    private boolean isValid = true;

    public CarmesiPanel(Component component) {
        this.component = component;
    }

    public ComponentValidator getValidator() {
        return validator;
    }

    public CarmesiPanel setComponentValidator(ComponentValidator validator) {
        this.validator = validator;
        return this;
    }

    @Override
    public Component getComponent() {
        return component;
    }

    @Override
    public HelpCtx getHelp() {
        return HelpCtx.DEFAULT_HELP;
    }

    @Override
    public void readSettings(WizardDescriptor data) {
    }

    @Override
    public void storeSettings(WizardDescriptor data) {
    }

    @Override
    public boolean isValid() {
        try {
            validator.validate(component);
            isValid = true;
        } catch (IllegalArgumentException ex) {
            isValid = false;
        }
        return isValid;
    }
    
    @Override
    public void addChangeListener(ChangeListener l) {
        listeners.add(l);
    }
    
    @Override
    public void removeChangeListener(ChangeListener l) {
        listeners.remove(l);
    }
    
    public void fireChangeEvent() {
        Iterator<ChangeListener> it=listeners.iterator();
        ChangeEvent ev = new ChangeEvent(this);
        while (it.hasNext()) {
            it.next().stateChanged(ev);
        }
    }
    
}
